<template>
  <div>
    <el-card>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      <el-form
        :inline="true"
        :model="userQuery"
        class="demo-form-inline"
        style="margin-top: 20px"
        size="large"
      >
        <el-form-item label="昵称">
          <el-input
            v-model="userQuery.nickname"
            placeholder="请输入昵称进行搜索"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getUserListData">搜索</el-button
          >&nbsp;&nbsp;
          <el-button type="success" @click="dialogVisible = true"
            >+新增用户</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-table :data="userList" style="width: 100%">
        <el-table-column prop="adminname" label="用户名" />
        <el-table-column prop="nickname" label="用户昵称" />
        <el-table-column label="用户头像">
          <!-- 使用作用域插槽，用来 自定义 该列的显示 -->
          <template #default="scope">
            <img style="width: 70px; height: 70px" :src="scope.row.avatar" />
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="edit(scope.row)">修改</el-button>
            <el-button type="danger" @click="del(scope.row.adminid)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="userQuery.page"
        v-model:page-size="userQuery.pageSize"
        :page-sizes="[1, 2, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="getUserListData"
        @current-change="getUserListData"
      />
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      :title="mode === 'add' ? '新增用户' : '修改用户'"
      width="800px"
      @close="close"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        size="large"
        status-icon
      >
        <el-form-item label="用户名" prop="adminname">
          <el-input v-model="ruleForm.adminname" :disabled="mode === 'edit'" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="ruleForm.nickname" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="ruleForm.status"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<!-- <script lang="ts">
export default {
  name: 'UserList'
}
</script> -->

<script setup lang="ts" name="UserList">
import { ref, reactive } from 'vue'
import { getUserList, addUser, updateUser, delUser } from '@/api/user'
import { User, UserForm } from '@/types/user'

import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

// const language = ref('zh-cn')
// const locale = computed(() => (language.value === 'zh-cn' ? zhCn : en))

const dialogVisible = ref(false)

const userQuery = ref({
  nickname: '',
  page: 1,
  pageSize: 2
})

const total = ref(0)

const userList = ref([] as User[])

const getUserListData = async () => {
  const res = await getUserList(userQuery.value)

  total.value = res.data.data.total
  userList.value = res.data.data.items
}

getUserListData()

/********************下面是新增&修改的内容************************* */
const mode = ref<'add' | 'edit'>('add')

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<UserForm>({
  adminname: '',
  nickname: '',
  status: 1
})

const rules = reactive<FormRules<UserForm>>({
  adminname: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    {
      min: 5,
      max: 15,
      message: '用户名的长度应该在5-15位之间',
      trigger: 'blur'
    }
  ],
  nickname: [
    { required: true, message: '昵称不能为空', trigger: 'blur' },
    {
      min: 5,
      max: 15,
      message: '昵称的长度应该在5-15位之间',
      trigger: 'blur'
    }
  ]
})

const edit = (row: User) => {
  mode.value = 'edit'
  // 这样子赋值会形成浅拷贝
  /**
   * 浅拷贝：一个对象直接赋值给另外一个对象，他们的内存地址指向同一块内存空间
   * 深拷贝：一个对象经过深拷贝赋值给另外一个对象之后，该了另外一个对象，之前的对象不受影响
   *
   * 深拷贝的实现方式：
   * 1、递归（完全深拷贝）
   * 2、JSON转换（完全深拷贝）
   * 3、Object.assign（不完全深拷贝、只拷贝一层）
   * 4、{...对象} 展开运算符（不完全深拷贝、只拷贝一层）
   */
  ruleForm.value = { ...row }
  // ruleForm = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
}

// 提交
const submit = () => {
  if (ruleFormRef.value) {
    ruleFormRef.value.validate(async valid => {
      if (!valid) return

      mode.value === 'add'
        ? await addUser(ruleForm.value)
        : await updateUser(ruleForm.value)

      // 提示
      ElMessage.success(mode.value === 'add' ? '新增成功~' : '修改成功')

      // 重新查询第一页数据
      if (mode.value === 'add') {
        userQuery.value.page = 1
      }
      getUserListData()

      // 关闭弹框
      dialogVisible.value = false
    })
  }
}

const close = () => {
  mode.value = 'add'
  if (ruleFormRef.value) {
    // 只是清空了校验
    ruleFormRef.value.resetFields()

    // 重置表单的模型时
    ruleForm.value = {
      adminid: '',
      adminname: '',
      nickname: '',
      status: 1
    }
  }
}

// 删除用户
const del = (adminid: string) => {
  ElMessageBox.confirm('确定删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await delUser(adminid)

      // 重新查询
      getUserListData()

      // 提示
      ElMessage.success('删除成功~')
    })
    .catch(() => {})
}
</script>

<style scoped></style>
